# -*- coding: utf-8 -*-

import paramiko
import select

from .ssh_conn_setting import SSH_CONNS, SSH_COMMANDS


def singleton(cls, *args, **kw):
    instances = {}

    def _singleton():
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return _singleton


# @singleton
class SSHConn(object):
    channel_list = []

    def __init__(self):
        for (key, value) in SSH_CONNS.items():
            self.conn(key, value)

    def conn(self, server, dpparms):
        # 进行连接
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(**dpparms)
        # 开启channel 管道
        transport = client.get_transport()
        channel = transport.open_session()
        channel.get_pty()
        # 将命令传入管道中
        channel.exec_command(SSH_COMMANDS[server])
        # self.channel = channel
        self.channel_list.append(channel)

    def read_log(self, ws, func):
        # 建立连接
        for channel in self.channel_list:
            # channel = SSHConn().channel
            while True:
                # 判断退出的准备状态
                if channel.exit_status_ready():
                    break
                # if command == "exit":
                #     channel.send("\x03")
                #     break
                try:
                    rl, wl, el = select.select([channel], [], [])
                    if len(rl) > 0:
                        # 设置大一点10MB 防止取半截日志 由于前端正则匹配日志，所以半截的会被忽略
                        recv = channel.recv(1024*100)
                        content = recv.decode('utf-8', 'ignore')
                        func(ws, content)
                # 键盘终端异常
                except KeyboardInterrupt:
                    channel.send("\x03")  # 发送 ctrl+c
                    channel.close()
            # client.close()
